#################################################
# Create country-year MID involvement data
#################################################

setwd("/Users/johanneskarreth/Documents/Dropbox/Uni/1 - Papers/36 - Democratic reversals/Paper/Project/JPR submission/R&R/Data analysis/")
mid4 <- read_csv("Source/MID 4.3/MIDB 4.3.csv")

head(arrange(mid4, dispnum4))

mid4$fatalmid <- ifelse(mid4$fatality > 0, 1, 0)
mid4$terrmid <- ifelse(mid4$revtype1 == 1 | mid4$revtype2 == 1, 1, 0)

mid4 <- mid4[, c("ccode", "dispnum3", "styear", "endyear", "fatality", "hiact", "hostlev", "fatalmid", "terrmid")]

mid4$midLength <- round((mid4$endyear - mid4$styear) + 1, digits = 0)

mid4_cy <- data.frame(ccode = rep(mid4$ccode, mid4$midLength), 
                      mid_startyear = rep(mid4$styear, mid4$midLength), 
                      mid_endyear = rep(mid4$endyear, mid4$midLength), 
                      mid = 1, 
                      DispNum3 = rep(mid4$dispnum3, mid4$midLength),
                      fatalmid = rep(mid4$fatalmid, mid4$midLength), 
                      terrmid = rep(mid4$terrmid, mid4$midLength), 
                      midLength = rep(mid4$midLength, mid4$midLength))

# Next: create year indicator
# then: drop duplicate country years, use max. values for everything

mid4_cy <- mutate(group_by(mid4_cy, ccode, DispNum3, add = FALSE), midYrCount = cumsum(mid))
mid4_cy <- ungroup(mid4_cy)
mid4_cy$year <- (mid4_cy$mid_startyear + mid4_cy$midYrCount) - 1

# Careful here: need to give the new vars new names, otherwise
# they just overwrite

mid4_cy <- summarize(.data = group_by(mid4_cy, ccode, year, add = FALSE),
                     midOngoing = max(mid),
                     midSum = sum(mid),
                     fatalmidOngoing = max(fatalmid),
                     fatalmidSum = sum(fatalmid),
                     terrmidOngoing = max(terrmid),
                     terrmidSum = sum(terrmid))

mid4_cy <- arrange(mid4_cy, ccode, year)

write.csv(mid4_cy, file = "Source/mid4_3.csv", row.names = FALSE)